PHP Core / OOPs / Multiple inheritance
Multiple Inheritance
-
Note
Unlike some other programming languages like C++, PHP does not allow a class to extend multiple classes simultaneously. This limitation is intentional and is due to potential complexities and ambiguities that can arise from multiple inheritance.
However, PHP offers alternative mechanisms to achieve similar functionality:
TraitsTraits are a mechanism for code reuse in single inheritance languages such as PHP. A trait is similar to a class, but it is intended to group functionality in a fine-grained and consistent way. Classes can use multiple traits, thus providing a form of multiple inheritance. However, traits cannot have properties.
Compositiontrait Trait1 { public function methodFromTrait1() { echo "Method from Trait1"; } } trait Trait2 { public function methodFromTrait2() { echo "Method from Trait2"; } } class MyClass { use Trait1, Trait2; } $obj = new MyClass(); $obj->methodFromTrait1(); // Output: Method from Trait1 $obj->methodFromTrait2(); // Output: Method from Trait2 Instead of inheriting behavior from multiple classes, you can create instances of multiple classes within a single class and delegate functionality accordingly. This is sometimes referred to as "composition over inheritance."
class Class1 { public function methodFromClass1() { echo "Method from Class1"; } } class Class2 { public function methodFromClass2() { echo "Method from Class2"; } } class MyClass { private $class1; private $class2; public function __construct() { $this->class1 = new Class1(); $this->class2 = new Class2(); } public function methodFromClass1() { $this->class1->methodFromClass1(); } public function methodFromClass2() { $this->class2->methodFromClass2(); } } $obj = new MyClass(); $obj->methodFromClass1(); // Output: Method from Class1 $obj->methodFromClass2(); // Output: Method from Class2